package com.maxmlr.music.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 * @Package com.maxmlr.music.util
 * @ClassName WebLogAspect
 * @Description TODO
 * @author max
 * @since 2018年12月19日 下午8:48:45 
 * @version 1.0
 * @Copyright Copyright (c) 2018: www.maxmlr.com.
 */
@Aspect
@Slf4j
@Component
public class WebLogAspect {

	//@Pointcut("execution (* com.agree.web..*.* (..))")
	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	private void anyMethod() {
	} // 声明一个切入点，anyMethod为切入点名称

	
	/**
	 * 
	 * @Title doAround
	 * @Description 环绕通知
	 * @author max
	 * @since 2018年12月15日 下午6:13:09
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	@Around("anyMethod()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		Class declaringType = pjp.getTarget().getClass();// 类名

		// 记录下请求内容
		log.info("请求URL : " + request.getRequestURL().toString());
		log.info("请求HTTP_METHOD : " + request.getMethod());
		log.info("请求IP : " + request.getRemoteAddr());
		log.info("请求CLASS_METHOD : " + declaringType.getName() + "." + pjp.getSignature().getName());
		log.info("请求参数ARGS : " + JSON.toJSONString(pjp.getArgs()));
		StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 开始
        Object  retVal = pjp.proceed();
        stopWatch.stop();
        // 结束
        log.info("请求响应耗时: "+stopWatch.getTotalTimeMillis()+" ms");
        log.info("请求响应信息RESPONSE : " + JSON.toJSONString(retVal));
        return retVal;
	}
	
}